#pragma once
#include<iostream>
#include <fstream>
#include <sstream>
#include <filesystem>
#include <memory>
#include <unistd.h>
#include <time.h>
#include "Mutex.hpp"

namespace LogModule
{
    using namespace LockModule;
    std::string gPath = "./log/";//文件所在文件夹
    std::string gFilename = "log.txt";//文件名字

    enum class LogLevel
    {
        DEBUG = 1,
        INFO,
        WARNING,
        ERROR,
        FATAL
    };
    std::string CurrTime()
    {
        time_t time = ::time(nullptr);
        struct tm curr;
        localtime_r(&time, &curr); // 时间戳

        char buffer[1024];
        snprintf(buffer, sizeof(buffer), "%4d-%02d-%02d %02d:%02d:%02d",
        curr.tm_year + 1900,
        curr.tm_mon + 1,
        curr.tm_mday,
        curr.tm_hour,
        curr.tm_min,
        curr.tm_sec);

        return buffer;
    }
    std::string Level2String(LogLevel level)
    {
        switch (level)
        {
        case LogLevel::DEBUG:
            return "DEBUG";
        case LogLevel::INFO:
            return "INFO";
        case LogLevel::WARNING:
            return "WARNING";
        case LogLevel::ERROR:
            return "ERROR";
        case LogLevel::FATAL:
            return "FATAL";
        default:
            return "None";
        }
    }

    //刷新策略
    class LogStrategy
    {
    public:
        virtual ~LogStrategy() = default;
        virtual void SyncLog(const std::string& message) = 0;

    };

    //控制台策略
    class ConseleLogstrategy : public LogStrategy
    {
    public:
        ConseleLogstrategy()
        {}
        ~ConseleLogstrategy()
        {}
        void SyncLog(const std::string& message)
        {
            LockGuard lck(_mtx);
            std::cout  << message << std::endl;
        }
    private:
        Mutex _mtx;
    };

    //文件（磁盘）策略
    class FileLogStrategy : public LogStrategy
    {
    public:
        FileLogStrategy(const std::string &Path = gPath,const std::string &Filename = gFilename)
        :_logpath(Path),
        _logname(Filename)
        {
            // 确认_logpath是存在的.LockGuard lockguard(_lock);
            if (std::filesystem::exists(_logpath))
            {
                return;
            }
            try
            {
                std::filesystem::create_directories(_logpath);
            }
            catch (std::filesystem::filesystem_error &e)
            
            {
                std::cerr << e.what() << "\n";
            }
        }
        ~FileLogStrategy()
        {}
        void SyncLog(const std::string& message)
        {
            LockGuard lck(_mtx);
            std::string logpath = _logpath + _logname;
            std::ofstream out(logpath,std::ios::app) ;
            if(!out.is_open())
            {
                return;
            }
            out << message << "\n";
            out.close();
        }
    private:
        std::string _logpath;
        std::string _logname;
        Mutex _mtx;
    };

    // 日志类
    class Logger
    {
    public:
        Logger()
        {
            //默认日志刷新策略为控制台
            _strategy = std::make_shared<ConseleLogstrategy>();
        }
        void EnableConsoleLog()
        {
            _strategy = std::make_shared<ConseleLogstrategy>();
        }
        void EnableFileLog()
        {
            _strategy = std::make_shared<FileLogStrategy>();
        }
        // 一条完整的信息: [2024-08-04 12:27:03] [DEBUG] [202938] [main.cc] [16] + 日志的可变部分(<< "hello world" << 3.14 << a << b;)
        class LogMessage
        {
        public:
            LogMessage(LogLevel level, const std::string &filename, int line,Logger& logger)
            :_Currtime(CurrTime()),
            _Level(level),
            _Pid(getpid()),
            _Filename(filename),
            _Line(line),
            _Logger(logger)
            {
                std::stringstream ssbuffer;
                ssbuffer << "[" << _Currtime << "] "
                         << "[" << Level2String(_Level) << "] "
                         << "[" << _Pid << "] "
                         << "[" << _Filename << "] "
                         << "[" << _Line << "] - ";
                _Loginfo = ssbuffer.str();
            }
            template<class T>
            LogMessage& operator<<(const T& message)
            {
                std::stringstream ssbuffer;
                ssbuffer << message;
                _Loginfo += ssbuffer.str();
                
                return *this;
            }

            ~LogMessage()
            {
                if (_Logger._strategy)
                {
                    _Logger._strategy->SyncLog(_Loginfo);                    
                }
            }
        private:
            std::string _Currtime;
            LogLevel _Level; 
            pid_t _Pid;
            std::string _Filename;
            int _Line;
            Logger &_Logger;
            std::string _Loginfo;
        };
        LogMessage operator()(LogLevel level, const std::string &filename, int line)
        {
            return LogMessage(level,filename,line,*this);
        }

        ~Logger()
        {}
    private:
        std::shared_ptr<LogStrategy> _strategy; // 日志刷新的策略方案
    };
    Logger logger;

    #define LOG(Level) logger(Level, __FILE__, __LINE__)
    #define ENABLE_CONSOLE_LOG() logger.EnableConsoleLog()
    #define ENABLE_FILE_LOG() logger.EnableFileLog()
}